﻿using System;
using System.Linq;

namespace FBGraph.ClientGenerator.CodeGen
{
    public class ImplementationList : CodeGenObjectList<TypeReference>
    {
        public ImplementationList() : base(", ") { }

        public void Suggest(Type type)
        {
            Suggest(new TypeReference(type));
        }

        public void Suggest(TypeReference suggested)
        {
            var existing = this.SingleOrDefault(t => t.Name == suggested.Name);
            if (existing == null)
            {   // new interface, add it
                this.Add(suggested);
                return;
            }
            else if (existing.TypeArguments.SequenceEqual(suggested.TypeArguments))
            {   // exact interface already exists, ignore it
                return;
            }
            else if (existing.TypeArguments.Count != suggested.TypeArguments.Count)
            {   // interfaces have different generic signatures, add it
                this.Add(suggested);
                return;
            }
            else if (existing.TypeArguments.Count == 1)
            {
                if (existing.TypeArguments[0].Type == typeof(String))
                {   // use the more specific suggestion, replace existing with suggestion
                    this.Remove(existing);
                    this.Add(suggested);
                    return;
                }
                else if (suggested.TypeArguments[0].Type == typeof(String))
                {   // keep the more specific suggestion, ignore it
                    return;
                }
                else
                {   // use the more recent suggestion, replace existing with suggestion
                    this.Remove(existing);
                    this.Add(suggested);
                }
            }
            else
            {   // don't know what to do here yet, but it shouldn't happen in the current configuration
                throw new InvalidOperationException();
            }
        }
    }
}